package com.epalmpay.service.profitmanage.impl;

import com.epalmpay.exception.ApplicationException;
import com.epalmpay.status.Rescode;
import com.epalmpay.dto.profitmanage.*;

import com.epalmpay.dto.system.BaseOutDTO;
import com.epalmpay.dto.yunliu.profit.*;
import com.epalmpay.entity.*;
import com.epalmpay.entity.profit.*;
import com.epalmpay.entity.profit.ProfitAgentMonth;
import com.epalmpay.entity.profit.ProfitMemberMonth;
import com.epalmpay.entity.profit.ProfitShopMonth;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.enumdef.ProfitEnum;
import com.epalmpay.mapper.*;
import com.epalmpay.mapper.profit.*;
import com.epalmpay.service.profitmanage.IProfitManageService;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.util.*;
import com.epalmpay.util.payplat.UtilFun;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by wzq on 2017/6/2.
 */
@Service("profitmanageService")
public class ProfitManageServiceImpl implements IProfitManageService {

	protected Logger logger = Logger.getLogger(this.getClass());

    @Resource
    private ProfitMapper profitMapper;
	@Resource
	private AgentMapper agentMapper;
	@Resource
	private GroupMapper groupMapper;
	@Resource
	private ShopMapper shopMapper;
	@Resource
	private MemberMapper memberMapper;
	@Resource
	private ProfitGroupMonthMapper profitGroupMonthMapper;
    @Resource
	private ProfitAgentMonthDetailMapper profitAgentMonthDetailMapper;
	@Resource
	private ProfitAgentDayDetailMapper profitAgentDayDetailMapper;
    @Resource
	private ProfitAgentMonthMapper profitAgentMonthMapper;
	@Resource
	private TradeOfflineMapper tradeOfflineMapper;
	@Resource
	private ProfitShopMonthDetailMapper profitShopMonthDetailMapper;
	@Resource
	private ProfitShopMonthMapper profitShopMonthMapper;
	@Resource
	private ProfitShopDayDetailMapper profitShopDayDetailMapper;
	@Resource
	private ShopGroupRelationMapper shopGroupRelationMapper;
	@Resource
	private ProfitGroupMonthDetailMapper profitGroupMonthDetailMapper;
	@Resource
	private ProfitGroupDayDetailMapper profitGroupDayDetailMapper;
	@Resource
	private ProfitMemberMonthMapper profitMemberMonthMapper;
	@Resource
	private YsObdProfitRuleMapper ysObdProfitRuleMapper;
	@Resource
	private YsOpenCreditProfitRuleMapper openCreditCardProfitRuleMapper;
	@Resource
	private YsPolicyProfitRuleMapper policyProfitRuleMapper;
	@Resource
	private YsPolicyProfitCityMapper policyProfitCityMapper;

	@Resource
	private YsCityMapper ysCityMapper;

	@Resource
	private YsObdMapper ysObdMapper;
	@Resource
	private YsOpenCreditProfitRuleMapper ysOpenCreditProfitRuleMapper;

	@Resource
	private YsPolicyOrderMapper ysPolicyOrderMapper;
	
	@Resource
	private IWalletService walletService;

	@Value("${YUNSTREAM_GROUP_ID}")
	private Long ysGroupId;

    public ProfitListOutDTO getProfitList(ProfitInDTO profitInDTO,Page page) throws Exception{
    	
    	ProfitListOutDTO result = new ProfitListOutDTO();
    	
    	Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId", profitInDTO.getGroupId());
		param.put("loginAgentId", profitInDTO.getLoginAgentId());
		param.put("loginShopId", profitInDTO.getLoginShopId());
		param.put("profitType", profitInDTO.getProfitType());
		param.put("profitStatus", profitInDTO.getProfitStatus());
		param.put("startDate", profitInDTO.getStartDate());//有待输入当前月份
		param.put("endDate", profitInDTO.getEndDate());
		param.put("name", profitInDTO.getName());

		int sumCount = profitMapper.selectProfitListCount(param);
		page.setTotalResult(sumCount);
		result.setSumCount(sumCount);
		if(sumCount<=0)
			return result;


		param.put("limit", page.getShowCount());
		param.put("start", page.getShowCount() * (page.getCurrentPage() - 1));


		try {
			List<Profit> profitlist = profitMapper.selectProfitList(param);
			result.setProfitList(profitlist);

			//取得代理商级别
			if (profitInDTO.getLoginAgentId() != null) {
				result.setLoginAgentLevel(agentMapper.selectByPrimaryKey(profitInDTO.getLoginAgentId()).getAgentLevel());
			}
		}catch (Exception e) {
			e.printStackTrace();
		}

		return result;

    }

	public ProfitListOutDTO getGroupStatis(ProfitInDTO profitInDTO) throws Exception{
		ProfitListOutDTO result = new ProfitListOutDTO();

		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId", profitInDTO.getGroupId());
		param.put("profitStatus", profitInDTO.getProfitStatus());
		if(profitInDTO.getStatisDate() !=null){
			param.put("statisDate", profitInDTO.getStatisDate().replace("-",""));//有待输入当前月份
		}
		param.put("name", profitInDTO.getName());

		int sumCount = profitGroupMonthMapper.selectMonthProfitListCount(param);
		result.setSumCount(sumCount);
		if(sumCount<=0)
			return result;

		param.put("limit", profitInDTO.getPageSize());

		param.put("start", profitInDTO.getPageSize()*(profitInDTO.getPageNo()-1));

		result.setProfitGroupMonthDTOList(profitGroupMonthMapper.selectMonthProfitList(param));
		return result;

	}

	public ProfitAgentMonthDetailDTO toAgentProfitMonthDetailPage(ProfitInDTO profitInDTO) throws Exception{
		ProfitAgentMonthDetailDTO result = new ProfitAgentMonthDetailDTO();

		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId", profitInDTO.getGroupId());
		param.put("agentId", profitInDTO.getAgentId());
		//param.put("profitStatus", profitInDTO.getProfitStatus());
		param.put("statisDate", profitInDTO.getStatisDate());//有待输入当前月份
		//param.put("name", profitInDTO.getName());

		//取得当前代理月分润总额
		ProfitAgentMonthDetailDTO agentMonthProfit = profitAgentMonthMapper.selectAgentMonthProfit(param);
		if(agentMonthProfit != null){
			result.setId(agentMonthProfit.getId());
            result.setAgentId(agentMonthProfit.getAgentId());
            result.setAgentName(agentMonthProfit.getAgentName());
            result.setAgentLevel(agentMonthProfit.getAgentLevel());
            result.setProfit(agentMonthProfit.getProfit());
            result.setProfitStatus(agentMonthProfit.getProfitStatus());
            result.setUpdateAmount(agentMonthProfit.getUpdateAmount());
            result.setUpdateTime(agentMonthProfit.getUpdateTime());
            result.setRemark(agentMonthProfit.getRemark());
		}
        //分类分润值取得
		ProfitAgentMonthDetailDTO profitKinds = profitAgentMonthDetailMapper.selectKindsProfitByProfitType(param);
		if(profitKinds != null) {
			result.setTradeProfit(profitKinds.getTradeProfit());
			result.setPrePurchaseProfit(profitKinds.getPrePurchaseProfit());
			result.setObdProfit(profitKinds.getObdProfit());
			result.setPolicyProfit(profitKinds.getPolicyProfit());
			result.setCreditCardProfit(profitKinds.getCreditCardProfit());
		}

		if(profitInDTO.getTabSelect() != null && profitInDTO.getTabSelect() == 1) {
			//取得交易分润列表
			Map<String, Object> param1 = new HashMap<String, Object>();
			//param1.put("groupId", profitInDTO.getGroupId());
			param1.put("agentId", profitInDTO.getAgentId());
			param1.put("statisDate", profitInDTO.getStatisDate());//有待输入当前月份
			param1.put("tradeAgentId", profitInDTO.getTradeAgentId());
			param1.put("name", profitInDTO.getName());

			int sumCount = profitAgentMonthDetailMapper.selectAgentTradeProfitGroupByShopIdCount(param1);
			result.setSumCount(sumCount);
			if (sumCount > 0) {
				param1.put("limit", profitInDTO.getPageSize());
				param1.put("start", profitInDTO.getPageSize() * (profitInDTO.getPageNo() - 1));
				result.setProfitTradeDTOList(profitAgentMonthDetailMapper.selectAgentTradeProfitGroupByShopId(param1));
				//取得代理列表
				result.setTradeAgentList(profitAgentMonthDetailMapper.selectProfitTradeAgentList(param1));
			}
		}else if(profitInDTO.getTabSelect() != null && profitInDTO.getTabSelect() == 2) {
			//取得其它产品类分润
			Map<String, Object> param2 = new HashMap<String, Object>();
			//param1.put("groupId", profitInDTO.getGroupId());
			param2.put("agentId", profitInDTO.getAgentId());
			param2.put("otherAgentId", profitInDTO.getOtherAgentId());
			param2.put("otherShopId", profitInDTO.getOtherShopId());
			param2.put("statisDate", profitInDTO.getStatisDate());//有待输入当前月份
			param2.put("tradeAgentId", profitInDTO.getTradeAgentId());
			param2.put("otherName", profitInDTO.getOtherName());

			int sumCount = profitAgentMonthDetailMapper.selectAgentOtherProfitGroupByShopIdCount(param2);
			result.setSumCount(sumCount);
			if (sumCount > 0) {
				param2.put("limit", profitInDTO.getPageSize());
				param2.put("start", profitInDTO.getPageSize() * (profitInDTO.getPageNo() - 1));
				result.setProfitOtherDTOList(profitAgentMonthDetailMapper.selectAgentOtherProfitGroupByShopId(param2));
				result.setOtherAgentList(profitAgentMonthDetailMapper.selectProfitOtherAgentList(param2));
				result.setOtherShopList(profitAgentMonthDetailMapper.selectProfitOtherShopList(param2));
			}
		}
		return result;
	}

	public ProfitListOutDTO 	getAgentProfitMonthByYear(ProfitInDTO profitInDTO) throws Exception{
		ProfitListOutDTO result = new ProfitListOutDTO();

		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId", profitInDTO.getGroupId());
		param.put("agentId", profitInDTO.getAgentId());
		//param.put("profitStatus", profitInDTO.getProfitStatus());
		if(profitInDTO.getStatisDate() !=null){
			param.put("statisDate", profitInDTO.getStatisDate().replace("-",""));//有待输入当前月份
		}
		//param.put("name", profitInDTO.getName());

		//取得当前代理月分润总额
		List<ProfitAgentMonth> agentMonthProfit = profitAgentMonthMapper.selectAgentMonthProfitByYear(param);
		if(agentMonthProfit != null){
			result.setProfitAgentMonthList(agentMonthProfit);
		}

		return result;
	}

	public ProfitAgentMonthDetailDTO toGroupProfitMonthDetailPage(ProfitInDTO profitInDTO) throws Exception{
		ProfitAgentMonthDetailDTO result = new ProfitAgentMonthDetailDTO();

		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId", profitInDTO.getGroupId());
		param.put("statisDate", profitInDTO.getStatisDate());//有待输入当前月份

		//取得当前大商户月分润总额
		ProfitAgentMonthDetailDTO agentMonthProfit = profitGroupMonthMapper.selectGroupMonthProfit(param);
		if(agentMonthProfit != null){
			result.setGroupId(agentMonthProfit.getGroupId());
			result.setGroupName(agentMonthProfit.getGroupName());
			result.setId(agentMonthProfit.getId());
			result.setProfit(agentMonthProfit.getProfit());
			result.setProfitStatus(agentMonthProfit.getProfitStatus());
		}

		//分类分润值取得
		ProfitAgentMonthDetailDTO profitKinds = profitGroupMonthDetailMapper.selectKindsProfitByProfitType(param);
		if(profitKinds != null) {
			result.setTradeProfit(profitKinds.getTradeProfit());
			result.setPrePurchaseProfit(profitKinds.getPrePurchaseProfit());
			result.setObdProfit(profitKinds.getObdProfit());
			result.setPolicyProfit(profitKinds.getPolicyProfit());
			result.setCreditCardProfit(profitKinds.getCreditCardProfit());
		}

		if(profitInDTO.getTabSelect() == 1) {
			//取得交易分润列表
			Map<String, Object> param1 = new HashMap<String, Object>();
			param1.put("groupId", profitInDTO.getGroupId());
			//param1.put("agentId", profitInDTO.getAgentId());
			param1.put("statisDate", profitInDTO.getStatisDate());//有待输入当前月份
			param1.put("tradeAgentId", profitInDTO.getTradeAgentId());
			param1.put("name", profitInDTO.getName());

			int sumCount = profitGroupMonthDetailMapper.selectGroupTradeProfitGroupByShopIdCount(param1);
			result.setSumCount(sumCount);
			if (sumCount > 0) {
				param1.put("limit", profitInDTO.getPageSize());
				param1.put("start", profitInDTO.getPageSize() * (profitInDTO.getPageNo() - 1));
				result.setProfitTradeDTOList(profitGroupMonthDetailMapper.selectGroupTradeProfitGroupByShopId(param1));
				//取得代理列表
				result.setTradeAgentList(profitGroupMonthDetailMapper.selectProfitTradeAgentList(param1));
			}
		}else if(profitInDTO.getTabSelect() == 2) {
			//取得其它产品类分润
			Map<String, Object> param2 = new HashMap<String, Object>();
			param2.put("groupId", profitInDTO.getGroupId());
			//param2.put("agentId", profitInDTO.getAgentId());
			param2.put("otherAgentId", profitInDTO.getOtherAgentId());
			param2.put("otherShopId", profitInDTO.getOtherAgentId());
			param2.put("statisDate", profitInDTO.getStatisDate());//有待输入当前月份
			param2.put("tradeAgentId", profitInDTO.getTradeAgentId());
			param2.put("otherName", profitInDTO.getOtherName());

			int sumCount = profitGroupMonthDetailMapper.selectGroupOtherProfitGroupByShopIdCount(param2);
			result.setSumCount(sumCount);
			if (sumCount > 0) {
				param2.put("limit", profitInDTO.getPageSize());
				param2.put("start", profitInDTO.getPageSize() * (profitInDTO.getPageNo() - 1));
				result.setProfitOtherDTOList(profitGroupMonthDetailMapper.selectGroupOtherProfitGroupByShopId(param2));
				result.setOtherAgentList(profitGroupMonthDetailMapper.selectProfitOtherAgentList(param2));
				result.setOtherShopList(profitGroupMonthDetailMapper.selectProfitOtherShopList(param2));
			}
		}
		return result;
	}


	//确认分润金额
	public BaseOutDTO updateConfirmProfitAmount(ProfitInDTO profitInDTO) throws Exception{
    	BaseOutDTO result = new BaseOutDTO();
		ProfitAgentMonth profitAgentMonth = profitAgentMonthMapper.selectByPrimaryKey(profitInDTO.getId());
		//updateAgentProfitOutMoney(profitAgentMonth,profitInDTO.getLoginId());
		//余额增加操作
		StringBuffer sb = new StringBuffer();
		//取得代理商的虚拟卡号
		Agent agent = agentMapper.selectByPrimaryKey(profitAgentMonth.getAgentId());
		Group group = groupMapper.selectByPrimaryKey(profitAgentMonth.getGroupId());

		String OrgOrderNum = UtilFun.createOrderNum();
		Integer profit = profitAgentMonth.getProfit();
	    
		//插入线下交易表
		TradeOffline tradeOffline = new TradeOffline();
		tradeOffline.setGmtCreate(new Date());
		tradeOffline.setGmtModified(new Date());
		tradeOffline.setGroupId(profitAgentMonth.getGroupId());
		tradeOffline.setOrderId(OrgOrderNum);
		tradeOffline.setPayerId(group.getId());
		tradeOffline.setPayerName(group.getMerchantName());
		tradeOffline.setPayerType((byte) CommonEnum.UserType.BusinessManager.getType());
		tradeOffline.setReceiverId(agent.getId().toString());
		tradeOffline.setReceiverName(agent.getMerchantName());
		tradeOffline.setReceiverType((byte) CommonEnum.UserType.Agents.getType());
		tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Profit.getType());
		tradeOffline.setOrderAmount(profit);
		tradeOffline.setRealAmount(profit);
		tradeOffline.setPayerType((byte)BizEnum.PaymentType.Other.getType());
		tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Success.getType());
		tradeOffline.setIsWallet(Boolean.TRUE);
		tradeOffline.setInNetCompany((byte)BizEnum.InNetCompany.fuqianla.getType());
		tradeOfflineMapper.insertSelective(tradeOffline);

		ProfitAgentMonth recordUpdate = new ProfitAgentMonth();
		recordUpdate.setId(profitAgentMonth.getId());
		recordUpdate.setGmtModified(new Date());
		recordUpdate.setConfirmTime(new Date());
		recordUpdate.setConfirmUserid(profitInDTO.getLoginId());
		recordUpdate.setTradeId(tradeOffline.getId());
		//recordUpdate.setRechargeOrderId(payResult.getOrderId());
		recordUpdate.setProfitStatus(ProfitEnum.MonthProfitDealStatus.Confirmed.getType());
		profitAgentMonthMapper.updateByPrimaryKeySelective(recordUpdate);
		
	    walletService.updateUserLockedAmount(agent.getPacketNum(), group.getPayGroupCode(), agent.getUserId(), profit+"", "1", 0,OrgOrderNum);
    	return result;
	}

	//确认分润金额
	public int updateProfitAmount(ProfitAgentMonth profitAgentMonth) throws Exception{
		int result = profitAgentMonthMapper.updateProfitAmount(profitAgentMonth);

		return result;
	}

	@Override
	public int updateShopProfitAmount(ProfitShopMonth profitShopMonth) throws Exception {
		return profitShopMonthMapper.updateShopProfitAmount(profitShopMonth);
	}

	public int updateAgentProfitOutMoney(ProfitAgentMonth profitAgentMonth,Long loginId) throws Exception{
		//余额增加操作
		StringBuffer sb = new StringBuffer();
		//取得代理商的虚拟卡号
		Agent agent = agentMapper.selectByPrimaryKey(profitAgentMonth.getAgentId());
		Group group = groupMapper.selectByPrimaryKey(profitAgentMonth.getGroupId());

		String OrgOrderNum = UtilFun.createOrderNum();
		Integer profit = profitAgentMonth.getProfit();
		if(profit<=0)
			return 0;

		/*PayBalanceChange payBalanceChange = PayBalanceChange.initialize(group.getPayGroupCode(),
				agent.getPacketNum(),profit.toString(), "1",
				OrgOrderNum, DateUtils.getDateTimeString("yyyyMMddHHmmss"), StringUtil.getRandNumberStr(10), "156");
		PayResult payResult = IPayAPI.consumptionBalanceChange(payBalanceChange);
	    if(!payResult.getRespCode().equals("0000")) {
			throw new ApplicationException(Rescode.FAIL,sb.append("确认分润调用支付平台接口失败。(StatisAgentMonthId:")
					.append(profitAgentMonth.getId()).append(")").toString());
		}*/

		//插入线下交易表
		/*TradeOffline tradeOffline = new TradeOffline();
		tradeOffline.setGmtCreate(new Date());
		tradeOffline.setGmtModified(new Date());
		tradeOffline.setGroupId(profitAgentMonth.getGroupId());
		tradeOffline.setOrderId(OrgOrderNum);
		tradeOffline.setPayerId(group.getId());
		tradeOffline.setPayerName(group.getMerchantName());
		tradeOffline.setPayerType((byte) CommonEnum.UserType.BusinessManager.getType());
		tradeOffline.setReceiverId(agent.getId().toString());
		tradeOffline.setReceiverName(agent.getMerchantName());
		tradeOffline.setReceiverType((byte) CommonEnum.UserType.Agents.getType());
		tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Profit.getType());
		tradeOffline.setOrderAmount(profit);
		tradeOffline.setRealAmount(profit);
		tradeOffline.setPayerType((byte)BizEnum.PaymentType.Other.getType());
		tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Success.getType());
		tradeOffline.setIsWallet(Boolean.TRUE);
		tradeOffline.setInNetCompany((byte)BizEnum.InNetCompany.fuqianla.getType());
		int result = tradeOfflineMapper.insertSelective(tradeOffline);*/

		ProfitAgentMonth recordUpdate = new ProfitAgentMonth();
		recordUpdate.setId(profitAgentMonth.getId());
		recordUpdate.setGmtModified(new Date());
		recordUpdate.setConfirmTime(new Date());
		recordUpdate.setConfirmUserid(loginId);
		recordUpdate.setTradeId(null);
		//recordUpdate.setRechargeOrderId(payResult.getOrderId());
		recordUpdate.setProfitStatus(ProfitEnum.MonthProfitDealStatus.WaitingForConfirm.getType());
		int result = profitAgentMonthMapper.updateByPrimaryKeySelective(recordUpdate);

		return result;
	}

	public ProfitShopMonthDetailDTO toShopProfitMonthDetailPage(ProfitInDTO profitInDTO) throws Exception{
		ProfitShopMonthDetailDTO result = new ProfitShopMonthDetailDTO();

		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId", profitInDTO.getGroupId());
		param.put("shopId", profitInDTO.getShopId());
		//param.put("profitStatus", profitInDTO.getProfitStatus());
		param.put("statisDate", profitInDTO.getStatisDate());//有待输入当前月份
		//param.put("name", profitInDTO.getName());

		//取得当前门店月分润总额
		ProfitShopMonthDetailDTO shopMonthProfit = profitShopMonthMapper.selectShopMonthProfit(param);
		if(shopMonthProfit != null){
			result.setId(shopMonthProfit.getId());
			result.setShopId(shopMonthProfit.getShopId());
			result.setShopName(shopMonthProfit.getShopName());
			result.setProfit(shopMonthProfit.getProfit());
			result.setProfitStatus(shopMonthProfit.getProfitStatus());
			result.setUpdateAmount(shopMonthProfit.getUpdateAmount());
			result.setUpdateTime(shopMonthProfit.getUpdateTime());
			result.setRemark(shopMonthProfit.getRemark());
		}
		//分类分润值取得
		ProfitShopMonthDetailDTO profitKinds = profitShopMonthDetailMapper.selectKindsProfitByProfitType(param);
		if(profitKinds != null) {
			result.setTradeProfit(profitKinds.getTradeProfit());
			result.setPrePurchaseProfit(profitKinds.getPrePurchaseProfit());
			result.setObdProfit(profitKinds.getObdProfit());
			result.setPolicyProfit(profitKinds.getPolicyProfit());
			result.setCreditCardProfit(profitKinds.getCreditCardProfit());
		}

		//取得交易分润数据
		result.setProfitTradeDTO(profitShopMonthDetailMapper.selectShopTradeProfitGroupByShopId(param));
        //取得其它产品类分润
		result.setProfitOtherDTO(profitShopMonthDetailMapper.selectShopOtherProfitGroupByShopId(param));

		return result;
	}

	//确认分润金额
	public BaseOutDTO updateConfirmShopProfitAmount(ProfitInDTO profitInDTO) throws Exception{
		BaseOutDTO result = new BaseOutDTO();
		ProfitShopMonth profitshopMonth = profitShopMonthMapper.selectByPrimaryKey(profitInDTO.getId());
		updateShopProfitOutMoney(profitshopMonth,profitInDTO.getLoginId());
		return result;
	}


	public int updateShopProfitOutMoney(ProfitShopMonth profitshopMonth,Long loginId) throws Exception{
		//余额增加操作
		StringBuffer sb = new StringBuffer();
		//取得会员的虚拟卡号
		ShopGroupRelation shopGroupRelation = shopGroupRelationMapper.selectShopInfo(profitshopMonth.getGroupId(),profitshopMonth.getShopId());
		Shop shop = shopMapper.selectByPrimaryKey(profitshopMonth.getShopId());
		Group group = groupMapper.selectByPrimaryKey(profitshopMonth.getGroupId());

		String OrgOrderNum = UtilFun.createOrderNum();
		Integer profit = profitshopMonth.getProfit();
		if(profit<=0)
			return 0;

		/*PayBalanceChange payBalanceChange = PayBalanceChange.initialize(group.getPayGroupCode(),
				shopGroupRelation.getPayMerchantCode(),profit.toString(), "1",
				OrgOrderNum, DateUtils.getDateTimeString("yyyyMMddHHmmss"), StringUtil.getRandNumberStr(10), "156");
		PayResult payResult = IPayAPI.consumptionBalanceChangeMerchant(payBalanceChange);
		if(!payResult.getRespCode().equals("0000")) {
			throw new ApplicationException(Rescode.FAIL,sb.append("确认分润调用支付平台接口失败。(StatisShopMonthId:")
					.append(profitshopMonth.getId()).append(")").toString());
		}*/

		//插入线下交易表
		/*TradeOffline tradeOffline = new TradeOffline();
		tradeOffline.setGmtCreate(new Date());
		tradeOffline.setGmtModified(new Date());
		tradeOffline.setGroupId(profitshopMonth.getGroupId());
		tradeOffline.setOrderId(OrgOrderNum);
		tradeOffline.setPayerId(group.getId());
		tradeOffline.setPayerName(group.getMerchantName());
		tradeOffline.setPayerType((byte) CommonEnum.UserType.BusinessManager.getType());
		tradeOffline.setReceiverId(shop.getId().toString());
		tradeOffline.setReceiverName(shop.getMerchantName());
		tradeOffline.setReceiverType((byte) CommonEnum.UserType.Store.getType());
		tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Profit.getType());
		tradeOffline.setOrderAmount(profit);
		tradeOffline.setRealAmount(profit);
		tradeOffline.setPayerType((byte)BizEnum.PaymentType.Other.getType());
		tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Success.getType());
		tradeOffline.setIsWallet(Boolean.TRUE);
		tradeOffline.setInNetCompany((byte)BizEnum.InNetCompany.fuqianla.getType());
		int result = tradeOfflineMapper.insertSelective(tradeOffline);*/


		ProfitShopMonth recordUpdate = new ProfitShopMonth();
		recordUpdate.setId(profitshopMonth.getId());
		recordUpdate.setGmtModified(new Date());
		recordUpdate.setConfirmTime(new Date());
		recordUpdate.setConfirmUserid(loginId);
		recordUpdate.setTradeId(null);
		//recordUpdate.setRechargeOrderId(payResult.getOrderId());
		recordUpdate.setProfitStatus(ProfitEnum.MonthProfitDealStatus.WaitingForConfirm.getType());
		int result = profitShopMonthMapper.updateByPrimaryKeySelective(recordUpdate);

		return result;
	}

	public int updateMemberProfitOutMoney(ProfitMemberMonth record, Long loginId) throws Exception{
		//取得会员的虚拟卡号
		Member member = memberMapper.selectByPrimaryKey(record.getMemberId());
		Group group = groupMapper.selectByPrimaryKey(member.getGroupId());

		String OrgOrderNum = UtilFun.createOrderNum();
		record.setDevelopeProfit(record.getDevelopeProfit()==null?0:record.getDevelopeProfit());
		record.setRecommendProfit(record.getRecommendProfit()==null?0:record.getRecommendProfit());
		Integer amount = record.getDevelopeProfit() + record.getRecommendProfit();
		if(amount<=0)
			return 0;

		//插入线下交易表
		Date date = new Date();
		TradeOffline tradeOffline = new TradeOffline();
		tradeOffline.setGmtCreate(date);
		tradeOffline.setGmtModified(date);
		tradeOffline.setGroupId(record.getGroupId());
		tradeOffline.setOrderId(OrgOrderNum);
		tradeOffline.setPayerId(record.getGroupId());
		tradeOffline.setPayerName(group.getMerchantName());
		tradeOffline.setPayerType((byte) CommonEnum.UserType.BusinessManager.getType());
		tradeOffline.setReceiverId(member.getId().toString());
		tradeOffline.setReceiverName(member.getName());
		tradeOffline.setReceiverType((byte) CommonEnum.UserType.User.getType());
		tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Profit.getType());
		tradeOffline.setOrderAmount(amount);
		tradeOffline.setRealAmount(amount);
		tradeOffline.setPayerType((byte)BizEnum.PaymentType.Other.getType());
		tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Success.getType());
		tradeOffline.setIsWallet(true);
		tradeOffline.setInNetCompany((byte)BizEnum.InNetCompany.fuqianla.getType());
		int result = tradeOfflineMapper.insertSelective(tradeOffline);

		ProfitMemberMonth recordUpdate = new ProfitMemberMonth();
		recordUpdate.setId(record.getId());
		recordUpdate.setGmtModified(date);
		recordUpdate.setTradeId(tradeOffline.getId());
		recordUpdate.setProfitStatus(ProfitEnum.MonthProfitDealStatus.OutCashed.getType());
		result = profitMemberMonthMapper.updateByPrimaryKeySelective(recordUpdate);
		
		walletService.updateUserLockedAmount(member.getVirtualCard(), group.getPayGroupCode(), member.getUserId(), amount+"", "1", 0,OrgOrderNum);
		return result;

	}

	//查看分润代理门店交易日详情列表
	public ProfitTradeDayDetailDTO toProfitAgentShopTradeDayDetailList(ProfitInDTO profitInDTO) throws Exception{
		ProfitTradeDayDetailDTO result = new ProfitTradeDayDetailDTO();

		//取得当前代理门店分润总计
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("agentId", profitInDTO.getAgentId());
		param.put("shopId", profitInDTO.getShopId());
		param.put("statisDate", profitInDTO.getStatisDate());//有待输入当前月份

		ProfitTradeDTO profitTradeDTO = profitAgentMonthDetailMapper.selectAgentTradeProfitByShopId(param);
		if(profitTradeDTO == null)
			throw new ApplicationException("查询记录失败!");

		result.setShopId(profitTradeDTO.getShopId());
		result.setShopName(profitTradeDTO.getShopName());
		result.setAgentId(profitTradeDTO.getAgentId());
		result.setAgentName(profitTradeDTO.getAgentName());
		result.setAgentLevel(profitTradeDTO.getAgentLevel());
		profitTradeDTO.setTradeNum(profitTradeDTO.getTradeNum()==null?0:profitTradeDTO.getTradeNum());
		profitTradeDTO.setPrePurchaseAmount(profitTradeDTO.getPrePurchaseAmount()==null?0:profitTradeDTO.getPrePurchaseAmount());
		result.setOrderNum(profitTradeDTO.getTradeNum() + profitTradeDTO.getPrePurchaseNum());
		profitTradeDTO.setTradeAmount(profitTradeDTO.getTradeAmount()==null?0:profitTradeDTO.getTradeAmount());
		result.setOrderAmount(profitTradeDTO.getTradeAmount());
		profitTradeDTO.setTradeProfit(profitTradeDTO.getTradeProfit()==null?0:profitTradeDTO.getTradeProfit());
		profitTradeDTO.setPrePurchaseProfit(profitTradeDTO.getPrePurchaseProfit()==null?0:profitTradeDTO.getPrePurchaseProfit());
        result.setOrderProfit(profitTradeDTO.getTradeProfit() + profitTradeDTO.getPrePurchaseProfit());

		//取得当前代理门店分润日明细
		int sumCount = profitAgentDayDetailMapper.selectAgentShopTradeProfitDayListCount(param);
		result.setSumCount(sumCount);
		if(sumCount<=0)
			return result;

		param.put("limit", profitInDTO.getPageSize());
//		if(profitInDTO.getPageNo()<=0){
//			profitInDTO.setPageNo(1);
//		}
		param.put("start", profitInDTO.getPageSize()*(profitInDTO.getPageNo()-1));

		result.setProfitTradeDTOList(profitAgentDayDetailMapper.selectAgentShopTradeProfitDayList(param));
		//这里做下转换 方便导出表格
		for(int i= 0;i<result.getProfitTradeDTOList().size();i++){
			result.getProfitTradeDTOList().get(i).setCousomTradeAmount(result.getProfitTradeDTOList().get(i).getTradeAmount()-profitTradeDTO.getPrePurchaseAmount());
			result.getProfitTradeDTOList().get(i).setPrifitTotalAmount(result.getProfitTradeDTOList().get(i).getTradeProfit()+result.getProfitTradeDTOList().get(i).getPrePurchaseProfit());
			result.getProfitTradeDTOList().get(i).setPrePurchaseAmount(profitTradeDTO.getPrePurchaseAmount()==null?0:profitTradeDTO.getPrePurchaseAmount());
		}

		return result;
	}

	public ProfitOtherDayDetailDTO toProfitAgentShopOtherDayDetailList(ProfitInDTO profitInDTO) throws Exception{
		ProfitOtherDayDetailDTO result = new ProfitOtherDayDetailDTO();
		//取得当前代理门店分润总计
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("agentId", profitInDTO.getAgentId());
		param.put("otherAgentId", profitInDTO.getProduceAgentId());
		param.put("otherShopId", profitInDTO.getProduceShopId());
		param.put("statisDate", profitInDTO.getStatisDate());//有待输入当前月份

		List<ProfitOtherDTO> profitOtherDTOList = profitAgentMonthDetailMapper.selectAgentOtherProfitGroupByShopId(param);
        if(profitOtherDTOList == null || profitOtherDTOList.size() < 1)
			throw new ApplicationException("查询记录失败!");
		ProfitOtherDTO profitOtherDTO = profitOtherDTOList.get(0);

		//门店
		if(profitOtherDTO.getShopId() != null)
		{
           result.setShopId(profitOtherDTO.getShopId());
           result.setShopName(profitOtherDTO.getShopName());
           //取得门店所属代理并赋值
           Agent agent = shopGroupRelationMapper.selectAgentByShopId(profitOtherDTO.getShopId(),profitInDTO.getGroupId());
           if(agent!=null) {
			   result.setAgentId(agent.getId());
			   result.setAgentName(agent.getMerchantName());
			   result.setAgentLevel(agent.getAgentLevel());
		   }
		}else{ //代理
		   result.setAgentId(profitOtherDTO.getAgentId());
		   result.setAgentName(profitOtherDTO.getAgentName());
		   result.setAgentLevel(profitOtherDTO.getAgentLevel());
		}
		result.setObdNum(profitOtherDTO.getObdNum());
		result.setObdProfit(profitOtherDTO.getObdProfit());
		result.setPolicyNum(profitOtherDTO.getPolicyNum());
		result.setPolicyProfit(profitOtherDTO.getPolicyProfit());
		result.setCreditNum(profitOtherDTO.getCreditNum());
		result.setCreditProfit(profitOtherDTO.getCreditProfit());


		//取得当前代理门店其它分润日明细
		int sumCount = profitAgentDayDetailMapper.selectAgentShopOtherProfitDayListCount(param);
		result.setSumCount(sumCount);
		if(sumCount<=0)
			return result;

		param.put("limit", profitInDTO.getPageSize());
		param.put("start", profitInDTO.getPageSize()*(profitInDTO.getPageNo()-1));

		result.setProfitOtherDTOList(profitAgentDayDetailMapper.selectAgentShopOtherProfitDayList(param));

		return result;
	}

	//查看分润门店交易日详情列表
	public ProfitTradeDayDetailDTO toProfitShopTradeDayDetailList(ProfitInDTO profitInDTO) throws Exception{
		ProfitTradeDayDetailDTO result = new ProfitTradeDayDetailDTO();

		//取得当前代理门店分润总计
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("shopId", profitInDTO.getShopId());
		param.put("statisDate", profitInDTO.getStatisDate());//有待输入当前月份

		ProfitTradeDTO profitTradeDTO = profitShopMonthDetailMapper.selectShopTradeProfitByShopId(param);
		if(profitTradeDTO == null)
			throw new ApplicationException("查询记录失败!");

		result.setShopId(profitTradeDTO.getShopId());
		result.setShopName(profitTradeDTO.getShopName());
		result.setAgentId(profitTradeDTO.getAgentId());
		result.setAgentName(profitTradeDTO.getAgentName());
		result.setAgentLevel(profitTradeDTO.getAgentLevel());
		profitTradeDTO.setTradeNum(profitTradeDTO.getTradeNum()==null?0:profitTradeDTO.getTradeNum());
		profitTradeDTO.setPrePurchaseAmount(profitTradeDTO.getPrePurchaseAmount()==null?0:profitTradeDTO.getPrePurchaseAmount());
		result.setOrderNum(profitTradeDTO.getTradeNum() + profitTradeDTO.getPrePurchaseNum());
		profitTradeDTO.setTradeAmount(profitTradeDTO.getTradeAmount()==null?0:profitTradeDTO.getTradeAmount());
		result.setOrderAmount(profitTradeDTO.getTradeAmount());
		profitTradeDTO.setTradeProfit(profitTradeDTO.getTradeProfit()==null?0:profitTradeDTO.getTradeProfit());
		profitTradeDTO.setPrePurchaseProfit(profitTradeDTO.getPrePurchaseProfit()==null?0:profitTradeDTO.getPrePurchaseProfit());
		result.setOrderProfit(profitTradeDTO.getTradeProfit() + profitTradeDTO.getPrePurchaseProfit());

		//取得当前门店分润日明细
		int sumCount = profitShopDayDetailMapper.selectShopTradeProfitDayListCount(param);
		result.setSumCount(sumCount);
		if(sumCount<=0)
			return result;

		param.put("limit", profitInDTO.getPageSize());
		param.put("start", profitInDTO.getPageSize()*(profitInDTO.getPageNo()-1));

		result.setProfitTradeDTOList(profitShopDayDetailMapper.selectShopTradeProfitDayList(param));

		return result;
	}

	//查看分润门店其它日详情列表
	public ProfitOtherDayDetailDTO toProfitShopOtherDayDetailList(ProfitInDTO profitInDTO) throws Exception{
		ProfitOtherDayDetailDTO result = new ProfitOtherDayDetailDTO();
		//取得当前代理门店分润总计
		Map<String,Object> param=new HashMap<String,Object>();
		//param.put("agentId", profitInDTO.getAgentId());
		//param.put("otherAgentId", profitInDTO.getProduceAgentId());
		param.put("shopId", profitInDTO.getProduceShopId());
		param.put("statisDate", profitInDTO.getStatisDate());//有待输入当前月份

		ProfitOtherDTO profitOtherDTO = profitShopMonthDetailMapper.selectShopOtherProfitGroupByShopId(param);
		if(profitOtherDTO == null)
			throw new ApplicationException("查询记录失败!");

		result.setShopId(profitOtherDTO.getShopId());
		result.setShopName(profitOtherDTO.getShopName());
		//取得门店所属代理并赋值
		Agent agent = shopGroupRelationMapper.selectAgentByShopId(profitOtherDTO.getShopId(),profitInDTO.getGroupId());
		if(agent!=null) {
			result.setAgentId(agent.getId());
			result.setAgentName(agent.getMerchantName());
			result.setAgentLevel(agent.getAgentLevel());
		}

		result.setObdNum(profitOtherDTO.getObdNum());
		result.setObdProfit(profitOtherDTO.getObdProfit());
		result.setPolicyNum(profitOtherDTO.getPolicyNum());
		result.setPolicyProfit(profitOtherDTO.getPolicyProfit());
		result.setCreditNum(profitOtherDTO.getCreditNum());
		result.setCreditProfit(profitOtherDTO.getCreditProfit());

		//取得当前门店其它分润日明细
		int sumCount = profitShopDayDetailMapper.selectShopOtherProfitDayListCount(param);
		result.setSumCount(sumCount);
		if(sumCount<=0)
			return result;

		param.put("limit", profitInDTO.getPageSize());
		param.put("start", profitInDTO.getPageSize()*(profitInDTO.getPageNo()-1));

		result.setProfitOtherDTOList(profitShopDayDetailMapper.selectShopOtherProfitDayList(param));

		return result;
	}

	public ProfitTradeDayDetailDTO toProfitGroupShopTradeDayDetailList(ProfitInDTO profitInDTO) throws Exception{
		ProfitTradeDayDetailDTO result = new ProfitTradeDayDetailDTO();

		//取得当前代理门店分润总计
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId", profitInDTO.getGroupId());
		param.put("shopId", profitInDTO.getShopId());
		param.put("statisDate", profitInDTO.getStatisDate());//有待输入当前月份

		ProfitTradeDTO profitTradeDTO = profitGroupMonthDetailMapper.selectGroupTradeProfitByShopId(param);
		if(profitTradeDTO == null)
			throw new ApplicationException("查询记录失败!");

		result.setShopId(profitTradeDTO.getShopId());
		result.setShopName(profitTradeDTO.getShopName());
		result.setAgentId(profitTradeDTO.getAgentId());
		result.setAgentName(profitTradeDTO.getAgentName());
		result.setAgentLevel(profitTradeDTO.getAgentLevel());
		profitTradeDTO.setTradeNum(profitTradeDTO.getTradeNum()==null?0:profitTradeDTO.getTradeNum());
		profitTradeDTO.setPrePurchaseAmount(profitTradeDTO.getPrePurchaseAmount()==null?0:profitTradeDTO.getPrePurchaseAmount());
		result.setOrderNum(profitTradeDTO.getTradeNum() + profitTradeDTO.getPrePurchaseNum());
		profitTradeDTO.setTradeAmount(profitTradeDTO.getTradeAmount()==null?0:profitTradeDTO.getTradeAmount());
		result.setOrderAmount(profitTradeDTO.getTradeAmount());
		profitTradeDTO.setTradeProfit(profitTradeDTO.getTradeProfit()==null?0:profitTradeDTO.getTradeProfit());
		profitTradeDTO.setPrePurchaseProfit(profitTradeDTO.getPrePurchaseProfit()==null?0:profitTradeDTO.getPrePurchaseProfit());
		result.setOrderProfit(profitTradeDTO.getTradeProfit() + profitTradeDTO.getPrePurchaseProfit());

		//取得当前代理门店分润日明细
		int sumCount = profitGroupDayDetailMapper.selectGroupShopTradeProfitDayListCount(param);
		result.setSumCount(sumCount);
		if(sumCount<=0)
			return result;

		param.put("limit", profitInDTO.getPageSize());
		param.put("start", profitInDTO.getPageSize()*(profitInDTO.getPageNo()-1));

		result.setProfitTradeDTOList(profitGroupDayDetailMapper.selectGroupShopTradeProfitDayList(param));
		//这里做下转换 方便导出表格
		for(int i= 0;i<result.getProfitTradeDTOList().size();i++){
			result.getProfitTradeDTOList().get(i).setCousomTradeAmount(result.getProfitTradeDTOList().get(i).getTradeAmount()-profitTradeDTO.getPrePurchaseAmount());
			result.getProfitTradeDTOList().get(i).setPrifitTotalAmount(result.getProfitTradeDTOList().get(i).getTradeProfit()+result.getProfitTradeDTOList().get(i).getPrePurchaseProfit());
			result.getProfitTradeDTOList().get(i).setPrePurchaseAmount(profitTradeDTO.getPrePurchaseAmount()==null?0:profitTradeDTO.getPrePurchaseAmount());
		}

		return result;
	}

	public ProfitOtherDayDetailDTO toProfitGroupShopOtherDayDetailList(ProfitInDTO profitInDTO) throws Exception{
		ProfitOtherDayDetailDTO result = new ProfitOtherDayDetailDTO();
		//取得当前代理门店分润总计
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("groupId", profitInDTO.getGroupId());
		param.put("otherAgentId", profitInDTO.getProduceAgentId());
		param.put("otherShopId", profitInDTO.getProduceShopId());
		param.put("statisDate", profitInDTO.getStatisDate());//有待输入当前月份

		List<ProfitOtherDTO> profitOtherDTOList = profitGroupMonthDetailMapper.selectGroupOtherProfitGroupByShopId(param);
		if(profitOtherDTOList == null || profitOtherDTOList.size() < 1)
			throw new ApplicationException("查询记录失败!");
		ProfitOtherDTO profitOtherDTO = profitOtherDTOList.get(0);

		//门店
		if(profitOtherDTO.getShopId() != null)
		{
			result.setShopId(profitOtherDTO.getShopId());
			result.setShopName(profitOtherDTO.getShopName());
			//取得门店所属代理并赋值
			Agent agent = shopGroupRelationMapper.selectAgentByShopId(profitOtherDTO.getShopId(),profitInDTO.getGroupId());
			if(agent!=null) {
				result.setAgentId(agent.getId());
				result.setAgentName(agent.getMerchantName());
				result.setAgentLevel(agent.getAgentLevel());
			}
		}else{ //代理
			result.setAgentId(profitOtherDTO.getAgentId());
			result.setAgentName(profitOtherDTO.getAgentName());
			result.setAgentLevel(profitOtherDTO.getAgentLevel());
		}
		result.setObdNum(profitOtherDTO.getObdNum());
		result.setObdProfit(profitOtherDTO.getObdProfit());
		result.setPolicyNum(profitOtherDTO.getPolicyNum());
		result.setPolicyProfit(profitOtherDTO.getPolicyProfit());
		result.setCreditNum(profitOtherDTO.getCreditNum());
		result.setCreditProfit(profitOtherDTO.getCreditProfit());

		//取得当前代理门店其它分润日明细
		int sumCount = profitGroupDayDetailMapper.selectGroupShopOtherProfitDayListCount(param);
		result.setSumCount(sumCount);
		if(sumCount<=0)
			return result;

		param.put("limit", profitInDTO.getPageSize());
		param.put("start", profitInDTO.getPageSize()*(profitInDTO.getPageNo()-1));

		result.setProfitOtherDTOList(profitGroupDayDetailMapper.selectGroupShopOtherProfitDayList(param));

		return result;
	}



	@Override
	public PolicyProfitRuleOutDTO GetPolicyProfitRule(YsPolicyProfitRule YsPolicyProfitRule) throws ApplicationException {
		PolicyProfitRuleOutDTO policyProfitRuleOutDTO=new PolicyProfitRuleOutDTO();
		YsPolicyProfitRule ysPolicyProfitRule1=policyProfitRuleMapper.selectPolicyProfitRuleByGroupId(YsPolicyProfitRule.getGroupId(),YsPolicyProfitRule.getType());
		try{
			PropertyCopyUtil.copyProperties(ysPolicyProfitRule1,policyProfitRuleOutDTO);
		}catch (Exception e){
			policyProfitRuleOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
		}
		return policyProfitRuleOutDTO;
	}

	@Override
	public OpenCreditCardProfitRuleOutDTO GetOpenCreditCardRule(YsOpenCreditProfitRule YsOpenCreditProfitRule) throws ApplicationException {
		OpenCreditCardProfitRuleOutDTO openCreditCardProfitRuleOutDTO=new OpenCreditCardProfitRuleOutDTO();
		YsOpenCreditProfitRule ysOpenCreditProfitRule1=openCreditCardProfitRuleMapper.selectOpenCreditCardProfitRuleByGroupId(YsOpenCreditProfitRule.getGroupId(),YsOpenCreditProfitRule.getType());
		try{
			PropertyCopyUtil.copyProperties(ysOpenCreditProfitRule1,openCreditCardProfitRuleOutDTO);
		}catch (Exception e){
			openCreditCardProfitRuleOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
		}
		return openCreditCardProfitRuleOutDTO;
	}

	@Override
	public PolicyProfitRuleOutDTO SetPolicyProfitRule(YsPolicyProfitRule ysPolicyProfitRule) throws ApplicationException {
		PolicyProfitRuleOutDTO policyProfitRuleOutDTO=new PolicyProfitRuleOutDTO();
		if (Tools.isEmpty(ysPolicyProfitRule.getId()+"")){
			ysPolicyProfitRule.setGmtCreate(new Date());
			ysPolicyProfitRule.setGmtModify(new Date());
			if (!Tools.isEmpty(ysPolicyProfitRule.getAgentId()+"")){
				YsPolicyProfitRule ysPolicyProfitRule1=policyProfitRuleMapper.selectByAgentId(ysPolicyProfitRule);

				if(ysPolicyProfitRule1!=null){
					ysPolicyProfitRule.setId(ysPolicyProfitRule1.getId());
					if ((ysPolicyProfitRule.getFlag()!=1)&&(ysPolicyProfitRule1.getReverseField1()!=0)){
						if (!Tools.isEmpty(ysPolicyProfitRule1.getProfit1()+"")){
							ysPolicyProfitRule.setProfit1(ysPolicyProfitRule1.getProfit1());
						}
						if (!Tools.isEmpty(ysPolicyProfitRule1.getProfit2()+"")){
							ysPolicyProfitRule.setProfit1(ysPolicyProfitRule1.getProfit2());
						}
						if (!Tools.isEmpty(ysPolicyProfitRule1.getProfit3()+"")){
							ysPolicyProfitRule.setProfit1(ysPolicyProfitRule1.getProfit3());
						}
						if (!Tools.isEmpty(ysPolicyProfitRule1.getPlatformProfit()+"")){
							ysPolicyProfitRule.setPlatformProfit(ysPolicyProfitRule1.getPlatformProfit());
						}
						if (!Tools.isEmpty(ysPolicyProfitRule1.getUserProfit()+"")){
							ysPolicyProfitRule.setUserProfit(ysPolicyProfitRule1.getUserProfit());
						}
					}else{
						YsPolicyProfitRule ysPolicyProfitRule2=policyProfitRuleMapper.selectCommonPolicyProfitRule(ysPolicyProfitRule.getGroupId());

						if (ysPolicyProfitRule2!=null){
							ysPolicyProfitRule.setProfit1(ysPolicyProfitRule2.getProfit1());
							ysPolicyProfitRule.setProfit2(ysPolicyProfitRule2.getProfit2());
							ysPolicyProfitRule.setProfit3(ysPolicyProfitRule2.getProfit3());
							ysPolicyProfitRule.setPlatformProfit(ysPolicyProfitRule2.getPlatformProfit());
							ysPolicyProfitRule.setUserProfit(ysPolicyProfitRule2.getUserProfit());
						}
					}

					int status=policyProfitRuleMapper.updateByPrimaryKeySelective(ysPolicyProfitRule);
					if (status>0)
					{
						policyProfitRuleOutDTO.setErrorCode(Rescode.SUCCESS, "设置成功");
					}
					return policyProfitRuleOutDTO;


				}else{
					if (ysPolicyProfitRule.getFlag()!=1){
						YsPolicyProfitRule ysPolicyProfitRule2=policyProfitRuleMapper.selectCommonPolicyProfitRule(ysPolicyProfitRule.getGroupId());

						if (ysPolicyProfitRule2!=null){
							ysPolicyProfitRule.setProfit1(ysPolicyProfitRule2.getProfit1());
							ysPolicyProfitRule.setProfit2(ysPolicyProfitRule2.getProfit2());
							ysPolicyProfitRule.setProfit3(ysPolicyProfitRule2.getProfit3());
							ysPolicyProfitRule.setPlatformProfit(ysPolicyProfitRule2.getPlatformProfit());
							ysPolicyProfitRule.setUserProfit(ysPolicyProfitRule2.getUserProfit());
						}
					}

					int status=policyProfitRuleMapper.insert(ysPolicyProfitRule);
					if (status>0)
					{
						policyProfitRuleOutDTO.setErrorCode(Rescode.SUCCESS, "设置成功");
					}
					return policyProfitRuleOutDTO;
				}

			}else{
				if (ysPolicyProfitRule.getFlag()!=1){
					YsPolicyProfitRule ysPolicyProfitRule3=policyProfitRuleMapper.selectCommonPolicyProfitRule(ysPolicyProfitRule.getGroupId());

					if (ysPolicyProfitRule3!=null){
						ysPolicyProfitRule.setProfit1(ysPolicyProfitRule3.getProfit1());
						ysPolicyProfitRule.setProfit2(ysPolicyProfitRule3.getProfit2());
						ysPolicyProfitRule.setProfit3(ysPolicyProfitRule3.getProfit3());
						ysPolicyProfitRule.setPlatformProfit(ysPolicyProfitRule3.getPlatformProfit());
						ysPolicyProfitRule.setUserProfit(ysPolicyProfitRule3.getUserProfit());
					}
				}

				int status=policyProfitRuleMapper.insert(ysPolicyProfitRule);
				if (status>0)
				{
					policyProfitRuleOutDTO.setErrorCode(Rescode.SUCCESS, "设置成功");
				}
				return policyProfitRuleOutDTO;
			}


		}else{
			ysPolicyProfitRule.setGmtModify(new Date());
			int status=policyProfitRuleMapper.updateByPrimaryKeySelective(ysPolicyProfitRule);
			if (status>0)
			{
				policyProfitRuleOutDTO.setErrorCode(Rescode.SUCCESS, "设置成功");
			}
			return policyProfitRuleOutDTO;
		}

	}

	@Override
	public PolicyProfitRuleOutDTO SetPolicyProfitCity(YsPolicyProfitCity ysObdProfitCity) throws ApplicationException {
		PolicyProfitRuleOutDTO policyProfitRuleOutDTO=new PolicyProfitRuleOutDTO();
		try{
			if (!Tools.isEmpty(ysObdProfitCity.getCityName())){
				YsCity ysCity=ysCityMapper.queryCityCode(ysObdProfitCity.getCityName());
				ysObdProfitCity.setCityCode(ysCity.getCityCode());
			}

			int	status=0;
			if (!Tools.isEmpty(ysObdProfitCity.getCityName())){
				ysObdProfitCity.setGmtCreate(new Date());
				status=policyProfitCityMapper.insert(ysObdProfitCity);
			}else{
				status=policyProfitCityMapper.updateByPrimaryKeySelective(ysObdProfitCity);

			}
			if (status>0){
				policyProfitRuleOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
			}else{
				policyProfitRuleOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
			}



		}catch (Exception e){
			policyProfitRuleOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
		}
		return policyProfitRuleOutDTO;
	}

	@Override
	public OpenCreditCardProfitRuleOutDTO SetOpenCreditCardRule(YsOpenCreditProfitRule ysOpenCreditProfitRule) throws ApplicationException {
		OpenCreditCardProfitRuleOutDTO openCreditCardProfitRuleOutDTO=new OpenCreditCardProfitRuleOutDTO();




		if (Tools.isEmpty(ysOpenCreditProfitRule.getId()+"")){
			ysOpenCreditProfitRule.setGmtCreate(new Date());
			ysOpenCreditProfitRule.setGmtModify(new Date());
			if (!Tools.isEmpty(ysOpenCreditProfitRule.getAgentId()+"")){
				YsOpenCreditProfitRule ysOpenCreditProfitRule1=openCreditCardProfitRuleMapper.selectByAgentId(ysOpenCreditProfitRule);

				if(ysOpenCreditProfitRule1!=null){
					ysOpenCreditProfitRule.setId(ysOpenCreditProfitRule1.getId());
					if ((ysOpenCreditProfitRule.getFlag()!=1)&&(ysOpenCreditProfitRule1.getReverseField1()!=0)){
						if (!Tools.isEmpty(ysOpenCreditProfitRule1.getProfit1()+"")){
							ysOpenCreditProfitRule.setProfit1(ysOpenCreditProfitRule1.getProfit1());
						}
						if (!Tools.isEmpty(ysOpenCreditProfitRule1.getProfit2()+"")){
							ysOpenCreditProfitRule.setProfit1(ysOpenCreditProfitRule1.getProfit2());
						}
						if (!Tools.isEmpty(ysOpenCreditProfitRule1.getProfit3()+"")){
							ysOpenCreditProfitRule.setProfit1(ysOpenCreditProfitRule1.getProfit3());
						}
						if (!Tools.isEmpty(ysOpenCreditProfitRule1.getPlatformProfit()+"")){
							ysOpenCreditProfitRule.setPlatformProfit(ysOpenCreditProfitRule1.getPlatformProfit());
						}
					}else{
						YsOpenCreditProfitRule ysOpenCreditProfitRule2=openCreditCardProfitRuleMapper.selectCommonProfitRule(ysOpenCreditProfitRule.getGroupId());

						if (ysOpenCreditProfitRule2!=null){
							ysOpenCreditProfitRule.setProfit1(ysOpenCreditProfitRule2.getProfit1());
							ysOpenCreditProfitRule.setProfit2(ysOpenCreditProfitRule2.getProfit2());
							ysOpenCreditProfitRule.setProfit3(ysOpenCreditProfitRule2.getProfit3());
							ysOpenCreditProfitRule.setPlatformProfit(ysOpenCreditProfitRule2.getPlatformProfit());

						}
					}


					int status=openCreditCardProfitRuleMapper.updateByPrimaryKeySelective(ysOpenCreditProfitRule);
					if (status>0)
					{
						openCreditCardProfitRuleOutDTO.setErrorCode(Rescode.SUCCESS, "设置成功");
					}
					return openCreditCardProfitRuleOutDTO;


				}else{
					if (ysOpenCreditProfitRule.getFlag()!=1){
						YsOpenCreditProfitRule ysOpenCreditProfitRule2=openCreditCardProfitRuleMapper.selectCommonProfitRule(ysOpenCreditProfitRule.getGroupId());

						if (ysOpenCreditProfitRule2!=null){
							ysOpenCreditProfitRule.setProfit1(ysOpenCreditProfitRule2.getProfit1());
							ysOpenCreditProfitRule.setProfit2(ysOpenCreditProfitRule2.getProfit2());
							ysOpenCreditProfitRule.setProfit3(ysOpenCreditProfitRule2.getProfit3());
							ysOpenCreditProfitRule.setPlatformProfit(ysOpenCreditProfitRule2.getPlatformProfit());

						}
					}

					int status=openCreditCardProfitRuleMapper.insert(ysOpenCreditProfitRule);
					if (status>0)
					{
						openCreditCardProfitRuleOutDTO.setErrorCode(Rescode.SUCCESS, "设置成功");
					}
					return openCreditCardProfitRuleOutDTO;
				}

			}else{
				if (ysOpenCreditProfitRule.getFlag()!=1){
					YsOpenCreditProfitRule ysOpenCreditProfitRule3=openCreditCardProfitRuleMapper.selectCommonProfitRule(ysOpenCreditProfitRule.getGroupId());

					if (ysOpenCreditProfitRule3!=null){
						ysOpenCreditProfitRule.setProfit1(ysOpenCreditProfitRule3.getProfit1());
						ysOpenCreditProfitRule.setProfit2(ysOpenCreditProfitRule3.getProfit2());
						ysOpenCreditProfitRule.setProfit3(ysOpenCreditProfitRule3.getProfit3());
						ysOpenCreditProfitRule.setPlatformProfit(ysOpenCreditProfitRule3.getPlatformProfit());

					}
				}

				int status=openCreditCardProfitRuleMapper.insert(ysOpenCreditProfitRule);
				if (status>0)
				{
					openCreditCardProfitRuleOutDTO.setErrorCode(Rescode.SUCCESS, "设置成功");
				}
				return openCreditCardProfitRuleOutDTO;
			}


		}else{
			ysOpenCreditProfitRule.setGmtModify(new Date());
			int status=openCreditCardProfitRuleMapper.updateByPrimaryKeySelective(ysOpenCreditProfitRule);
			if (status>0)
			{
				openCreditCardProfitRuleOutDTO.setErrorCode(Rescode.SUCCESS, "设置成功");
			}
			return openCreditCardProfitRuleOutDTO;
		}

	}


	@Override
	public PolicyProfitListOutDTO getPolicyList(YsPolicyProfitRule ysPolicyProfitRule) throws ApplicationException {
		PolicyProfitListOutDTO policyProfitListOutDTO=new PolicyProfitListOutDTO();
		try{
			List<YsPolicyProfitRule> list=policyProfitRuleMapper.queryYsPolicyProfitRuleList(ysPolicyProfitRule);
			policyProfitListOutDTO.setYsPolicyProfitRuleList(list);
			List<YsPolicyProfitCity> cityList=policyProfitCityMapper.queryYsPolicyProfitCityList(ysPolicyProfitRule.getGroupId());
			if (cityList.size()==0){
				YsPolicyProfitCity ysPolicyProfitCity=new YsPolicyProfitCity();
				ysPolicyProfitCity.setGmtCreate(new Date());
				ysPolicyProfitCity.setGmtModify(new Date());
				ysPolicyProfitCity.setCityCode("0000");
				ysPolicyProfitCity.setCityName("全国");
				ysPolicyProfitCity.setProfit(3000);
				//ysPolicyProfitCity.setValidTime(new Date());
				ysPolicyProfitCity.setGroupId(ysPolicyProfitRule.getGroupId());
				policyProfitCityMapper.insert(ysPolicyProfitCity);
				List<YsPolicyProfitCity> tempList=policyProfitCityMapper.queryYsPolicyProfitCityList(ysPolicyProfitRule.getGroupId());
				policyProfitListOutDTO.setYsPolicyProfitCityList(tempList);
			}else{
				policyProfitListOutDTO.setYsPolicyProfitCityList(cityList);
			}

			List<String> ysCityList=ysCityMapper.queryYsCityList();

			policyProfitListOutDTO.setYsCityList(ysCityList);

			return policyProfitListOutDTO;
		}catch (Exception e) {
			policyProfitListOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
			e.printStackTrace();
		}

		return policyProfitListOutDTO;
	}

	@Override
	public PolicyProfitRuleOutDTO deletePolicyProfitRule(YsPolicyProfitRule ysPolicyProfitRule) throws ApplicationException {
		PolicyProfitRuleOutDTO policyProfitRuleOutDTO=new PolicyProfitRuleOutDTO();
		int status=policyProfitRuleMapper.updateByPrimaryKeySelective(ysPolicyProfitRule);

		if (status>0)
		{
			policyProfitRuleOutDTO.setErrorCode(Rescode.SUCCESS, "删除成功");
		}
		return policyProfitRuleOutDTO;
	}

	@Override
	public PolicyProfitRuleOutDTO deletePolicyProfitCity(YsPolicyProfitCity ysPolicyProfitCity) throws ApplicationException {
		PolicyProfitRuleOutDTO policyProfitRuleOutDTO=new PolicyProfitRuleOutDTO();
		int status=policyProfitCityMapper.deleteByPrimaryKey(ysPolicyProfitCity.getId());
		if (status>0)
		{
			policyProfitRuleOutDTO.setErrorCode(Rescode.SUCCESS, "删除成功");
		}
		return policyProfitRuleOutDTO;
	}

	@Override
	public CreditCardOpenCardListOutDTO getCreditCardOpenCardList(YsOpenCreditProfitRule ysOpenCreditProfitRule) throws ApplicationException {
		CreditCardOpenCardListOutDTO creditCardOpenCardListOutDTO=new CreditCardOpenCardListOutDTO();
		try{
			List<YsOpenCreditProfitRule> list=openCreditCardProfitRuleMapper.queryYsOpenCreditProfitRuleList(ysOpenCreditProfitRule);
			creditCardOpenCardListOutDTO.setYsOpenCreditProfitRuleList(list);
			return creditCardOpenCardListOutDTO;
		}catch (Exception e) {
			creditCardOpenCardListOutDTO.setErrorCode(Rescode.DEFAULT_PREFIX, "处理出现异常");
			e.printStackTrace();
		}

		return creditCardOpenCardListOutDTO;
	}

	@Override
	public OpenCreditCardProfitRuleOutDTO deleteCreditCardOpenCardProfitRule(YsOpenCreditProfitRule ysOpenCreditProfitRule) throws ApplicationException {
		OpenCreditCardProfitRuleOutDTO openCreditCardProfitRuleOutDTO=new OpenCreditCardProfitRuleOutDTO();
		int status=openCreditCardProfitRuleMapper.updateByPrimaryKeySelective(ysOpenCreditProfitRule);
		if (status>0)
		{
			openCreditCardProfitRuleOutDTO.setErrorCode(Rescode.SUCCESS, "删除成功");
		}
		return openCreditCardProfitRuleOutDTO;
	}

	//obd分润计算处理
	@Override
	public int insertObdProfitCalculate(Long memberId,YsObd ysObd) throws Exception{
		int result = 0;

		Agent agent = null;
		Agent firstAgent = null;
		Agent secondAgent = null;
		Agent thirdAgent = null;
		Agent parentAgent = null;


		YsObdProfitRule rule = null;
		Date date = new Date();
		Profit profit = new Profit();

		Member member = memberMapper.selectByPrimaryKey(memberId);
		if(ysObd.getAgentId() != null ){
			agent = agentMapper.selectByPrimaryKey(ysObd.getAgentId());
			//如果为一级代理商
			if(agent.getAgentLevel()==1){
				firstAgent = agent;
			}else if(agent.getAgentLevel()==2){
				secondAgent = agent;
				firstAgent = agentMapper.selectParentAgentProfitInfoById(agent.getId());
			}else if(agent.getAgentLevel()==3){
				thirdAgent = agent;
				secondAgent = agentMapper.selectParentAgentProfitInfoById(agent.getId());
				firstAgent = agentMapper.selectParentAgentProfitInfoById(secondAgent.getId());
			}else if(agent.getAgentLevel()>3){
				throw new ApplicationException("会员(memberId:" + memberId + ")代理商等级超过3级!");
			}
		}else if(ysObd.getShopId() != null){
			parentAgent = agentMapper.selectAgentProfitInfoByShopId(ysObd.getShopId(),member.getGroupId());
			if(parentAgent.getAgentLevel() ==1){
				firstAgent = parentAgent;
			}else if(parentAgent.getAgentLevel() == 2){
				secondAgent = parentAgent;
				firstAgent = agentMapper.selectParentAgentProfitInfoById(parentAgent.getId());
			}
		}else{
			//代理或者门店发展会员以外的情况不处理分润
			return result;
		}

		//先查一级代理商
		rule = ysObdProfitRuleMapper.selectAgentValidRule(member.getGroupId(),firstAgent.getId());
		if(rule == null){
			rule = ysObdProfitRuleMapper.selectGroupValidRule(member.getGroupId());
		}
		if(rule==null)
			throw new ApplicationException("obd分润规则未设置!");

		Integer profit1 = 0;
		Integer profit2 = 0;
		Integer profit3 = 0;
		Integer totalProfit = 0;

		//如果有效期时间大于修改时间且交易月分
		String tradeMonth = DateUtil.fomatDate(date, DateUtil.sdfDayss);
		if(rule.getValidTime() != null && rule.getValidTime().compareTo(rule.getGmtModify()) > 0
				&& tradeMonth.equals(DateUtil.fomatDate(rule.getGmtModify(), DateUtil.sdfDayss))){
			//取老值
			profit1 = rule.getOldProfit1()==null?0:rule.getOldProfit1();
			profit2 = rule.getOldProfit2()==null?0:rule.getOldProfit2();
			profit3 = rule.getOldProfit2()==null?0:rule.getOldProfit3();
			totalProfit = rule.getOldTotalProfit()==null?0:rule.getOldTotalProfit();
		}else{
//			1代表立即生效
			if (Tools.isEmpty(rule.getReverseField2()+"")){
				//取新值
				profit1 = rule.getProfit1()==null?0:rule.getProfit1();
				profit2 = rule.getProfit2()==null?0:rule.getProfit2();
				profit3 = rule.getProfit3()==null?0:rule.getProfit3();
				totalProfit = rule.getTotalProfit()==null?0:rule.getTotalProfit();
			}else{
				if (rule.getReverseField2()==1){
					profit1 = rule.getNewProfit1()==null?0:rule.getNewProfit1();
					profit2 = rule.getNewProfit2()==null?0:rule.getNewProfit2();
					profit3 = rule.getNewProfit3()==null?0:rule.getNewProfit3();
					totalProfit = rule.getNewTotalProfit()==null?0:rule.getNewTotalProfit();
				}else{
					//取新值
					profit1 = rule.getProfit1()==null?0:rule.getProfit1();
					profit2 = rule.getProfit2()==null?0:rule.getProfit2();
					profit3 = rule.getProfit3()==null?0:rule.getProfit3();
					totalProfit = rule.getTotalProfit()==null?0:rule.getTotalProfit();
				}
			}


		}

		profit.setGmtCreate(date);
		profit.setGmtModified(date);
		profit.setGroupId(member.getGroupId());
		profit.setProfitType(ProfitEnum.ProfitType.OBD.getType());
		profit.setProfit(totalProfit);
		profit.setProduceMemberid(memberId);

		if(ysObd.getAgentId() != null){
			if(agent.getAgentLevel()==1){
				profit.setFirstAgentId(agent.getId());
				profit.setFirstAgentProfit((profit1+profit2+profit3));
			}else if(agent.getAgentLevel()==2){
				profit.setSecondAgentId(agent.getId());
				profit.setSecondAgentProfit((profit2+profit3));
				profit.setFirstAgentId(firstAgent.getId());
				profit.setFirstAgentProfit(profit1);
			}else if(agent.getAgentLevel()==3){
				profit.setThirdAgentId(agent.getId());
				profit.setThirdAgentProfit(profit3);
				profit.setSecondAgentId(secondAgent.getId());
				profit.setSecondAgentProfit((profit2));
				profit.setFirstAgentId(firstAgent.getId());
				profit.setFirstAgentProfit((profit1));
			}
			profit.setProduceAgentid(agent.getId());
		}else if(ysObd.getShopId() != null){
			profit.setShopId(ysObd.getShopId());
			profit.setShopProfit(profit3);
			profit.setProduceShopid(ysObd.getShopId());

			if(parentAgent.getAgentLevel() ==1){
				profit.setFirstAgentId(parentAgent.getId());
				profit.setFirstAgentProfit((profit1+profit2));
				profit.setProduceAgentid(parentAgent.getId());
			}else if(parentAgent.getAgentLevel() == 2){
				profit.setSecondAgentId(parentAgent.getId());
				profit.setSecondAgentProfit((profit2));
				profit.setFirstAgentId(firstAgent.getId());
				profit.setFirstAgentProfit(profit1);
			}
		}
		profit.setProfitStatus(ProfitEnum.ProfitStatus.Profited.getType());
		profit.setOrderId(ysObd.getId());
		profit.setOrderNo(ysObd.getDeviceId());
		profit.setMemberId(memberId);

		result = profitMapper.insert(profit);

		//更新obd的状态
		ysObd.setIsProfit(1);
		ysObdMapper.updateByPrimaryKeySelective(ysObd);
		return result;
	}

	//信用卡开卡分润计算
	public int insertCreditOpenCardProfitCalculate(String idNo,String creditCardNo) throws Exception{
		int result = 0;

		Agent agent = null;
		Agent firstAgent = null;
		Agent secondAgent = null;
		Agent thirdAgent = null;
		Shop shop = null;
		Agent parentAgent = null;

		YsOpenCreditProfitRule rule = null;
		Date date = new Date();
		Profit profit = new Profit();

		Member member = memberMapper.selectByIdNo(idNo,ysGroupId);
		if(member == null){
			throw new ApplicationException("查询会员(idNo:" + idNo + ")记录失败!");
		}
		int activateCount = ysObdMapper.selectMemberIdActivateCount(member.getId());
		if(activateCount == 0) {
			throw new ApplicationException("会员(idNo:" + idNo + ")尚未激活OBD!");
		}
		if(member.getFromType() == null){
			throw new ApplicationException("会员(idNo:" + idNo + ")没有发展来源类型!");
		}
		if(member.getFromType() == BizEnum.MemberDevelopeFrom.AgentDevelope.getType()){
			agent = agentMapper.selectByPrimaryKey(member.getFromId());
			if(agent.getAgentLevel()==1){
				firstAgent = agent;
			}else if(agent.getAgentLevel()==2){
				secondAgent = agent;
				firstAgent = agentMapper.selectParentAgentProfitInfoById(agent.getId());
			}else if(agent.getAgentLevel()==3){
				thirdAgent = agent;
				secondAgent = agentMapper.selectParentAgentProfitInfoById(agent.getId());
				firstAgent = agentMapper.selectParentAgentProfitInfoById(secondAgent.getId());
			}else if(agent.getAgentLevel()>3){
				throw new ApplicationException("会员(idNo:" + idNo + ")代理商等级超过3级!");
			}
		}else if(member.getFromType() == BizEnum.MemberDevelopeFrom.ShopDevelope.getType()){
			shop = shopMapper.selectByPrimaryKey(member.getFromId());
			parentAgent = agentMapper.selectAgentProfitInfoByShopId(shop.getId(),member.getGroupId());
			if(parentAgent.getAgentLevel() ==1){
				firstAgent = parentAgent;
			}else if(parentAgent.getAgentLevel() == 2){
				secondAgent = parentAgent;
				firstAgent = agentMapper.selectParentAgentProfitInfoById(parentAgent.getId());
			}
		}

		//先查一级代理商
		rule = ysOpenCreditProfitRuleMapper.selectAgentValidRule(member.getGroupId(),firstAgent.getId());
		if(rule == null){
			rule = ysOpenCreditProfitRuleMapper.selectGroupValidRule(member.getGroupId());
		}
		if(rule==null)
			throw new ApplicationException("信用卡开卡分润规则未设置!");

		Integer platformProfit = 0;
		Integer profit1 = 0;
		Integer profit2 = 0;
		Integer profit3 = 0;
		Integer totalProfit = 0;
		Long tmpProfit = 0L;//临时计算变量

		//如果有效期时间大于修改时间且交易月分
		String tradeMonth = DateUtil.fomatDate(date, DateUtil.sdfDayss);
		if(rule.getValidTime() != null && rule.getValidTime().compareTo(rule.getGmtModify()) > 0
				&& tradeMonth.equals(DateUtil.fomatDate(rule.getGmtModify(), DateUtil.sdfDayss))){
			//取老值
			platformProfit = rule.getOldPlatformProfit()==null?0:rule.getOldPlatformProfit();
			profit1 = rule.getOldProfit1()==null?0:rule.getOldProfit1();
			profit2 = rule.getOldProfit2()==null?0:rule.getOldProfit2();
			profit3 = rule.getOldProfit2()==null?0:rule.getOldProfit3();
			totalProfit = rule.getOldTotalProfit()==null?0:rule.getOldTotalProfit();
		}else{
			//取新值
			platformProfit = rule.getPlatformProfit()==null?0:rule.getPlatformProfit();
			profit1 = rule.getProfit1()==null?0:rule.getProfit1();
			profit2 = rule.getProfit2()==null?0:rule.getProfit2();
			profit3 = rule.getProfit3()==null?0:rule.getProfit3();
			totalProfit = rule.getTotalProfit()==null?0:rule.getTotalProfit();
		}

		profit.setGmtCreate(date);
		profit.setGmtModified(date);
		profit.setGroupId(member.getGroupId());
		profit.setProfitType(ProfitEnum.ProfitType.CreditCard.getType());
		profit.setProfit(totalProfit);
		tmpProfit = (Long.parseLong(totalProfit.toString())*platformProfit)/10000;
		profit.setGroupProfit(tmpProfit.intValue());
		profit.setProduceMemberid(member.getId());

		if(agent != null){
			if(agent.getAgentLevel()==1){
				profit.setFirstAgentId(agent.getId());
				tmpProfit = (Long.parseLong(totalProfit.toString())*(profit1+profit2+profit3))/10000;
				profit.setFirstAgentProfit(tmpProfit.intValue());
			}else if(agent.getAgentLevel()==2){
				profit.setSecondAgentId(agent.getId());
				tmpProfit = (Long.parseLong(totalProfit.toString())*(profit2+profit3))/10000;
				profit.setSecondAgentProfit(tmpProfit.intValue());
				profit.setFirstAgentId(firstAgent.getId());
				tmpProfit = (Long.parseLong(totalProfit.toString())*(profit1))/10000;
				profit.setFirstAgentProfit(tmpProfit.intValue());
			}else if(agent.getAgentLevel()==3){
				profit.setThirdAgentId(agent.getId());
				tmpProfit = (Long.parseLong(totalProfit.toString())*(profit3))/10000;
				profit.setThirdAgentProfit(tmpProfit.intValue());
				profit.setSecondAgentId(secondAgent.getId());
				tmpProfit = (Long.parseLong(totalProfit.toString())*(profit2))/10000;
				profit.setSecondAgentProfit(tmpProfit.intValue());
				profit.setFirstAgentId(firstAgent.getId());
				tmpProfit = (Long.parseLong(totalProfit.toString())*(profit1))/10000;
				profit.setFirstAgentProfit(tmpProfit.intValue());
			}
			profit.setProduceAgentid(agent.getId());
		}else if(shop != null){
			profit.setShopId(shop.getId());
			tmpProfit = (Long.parseLong(totalProfit.toString())*(profit3))/10000;
			profit.setShopProfit(tmpProfit.intValue());
			profit.setProduceShopid(shop.getId());

			if(parentAgent.getAgentLevel() ==1){
				profit.setFirstAgentId(parentAgent.getId());
				tmpProfit = (Long.parseLong(totalProfit.toString())*(profit1+profit2))/10000;
				profit.setFirstAgentProfit(tmpProfit.intValue());
				profit.setProduceAgentid(parentAgent.getId());
			}else if(parentAgent.getAgentLevel() == 2){
				profit.setSecondAgentId(parentAgent.getId());
				tmpProfit = (Long.parseLong(totalProfit.toString())*(profit2))/10000;
				profit.setSecondAgentProfit(tmpProfit.intValue());
				profit.setFirstAgentId(firstAgent.getId());
				tmpProfit = (Long.parseLong(totalProfit.toString())*(profit1))/10000;
				profit.setFirstAgentProfit(tmpProfit.intValue());
			}
		}
		profit.setProfitStatus(ProfitEnum.ProfitStatus.Profited.getType());
		//profit.setOrderId(ysObd.getId());
		profit.setOrderNo(creditCardNo);
		profit.setMemo(creditCardNo);
		//profit.setMemberId(memberId);

		result = profitMapper.insert(profit);

		return result;
	}

	//保单分润计算处理
	public int insertPolicyProfitCalculate(String policyId,String thirdUserId,Integer orderAmount,String areaCode,
									 String areaName,String idNo,String confirmTime,Integer policyStatus) throws Exception{
		int result = 0;

		Agent agent = null;
		Agent firstAgent = null;
		Agent secondAgent = null;
		Agent thirdAgent = null;
		Shop shop = null;
		Agent parentAgent = null;

		YsPolicyProfitRule rule = null;
		YsPolicyProfitCity city = null;
		Date date = new Date();
		Profit profit = new Profit();

		if(StringUtil.isEmpty(policyId)){
			throw new ApplicationException("保单号不能为空!");
		}
		if(StringUtil.isEmpty(thirdUserId)){
			throw new ApplicationException("会员(memberId:" + thirdUserId + ")不能为空!");
		}
		Member member=memberMapper.selectByThirdUserId(thirdUserId);
		if(member==null)
			throw new ApplicationException(Rescode.FAIL,"会员(memberId:" + thirdUserId +")不存在！");

		if(orderAmount == null || orderAmount <= 0){
			throw new ApplicationException("订单金额(orderAmount:" + orderAmount + ")不能为空!");
		}
		if(StringUtil.isEmpty(areaCode)){
			areaCode = "0000";
		}

		int count = ysPolicyOrderMapper.selectCountByPolicyId(policyId);
		if(count >0)
			throw new ApplicationException("保单号(policyId:" + policyId + ")已经处理过!");

		YsPolicyOrder policyOrder = new YsPolicyOrder();
		policyOrder.setGmtCreate(date);
		policyOrder.setGmtModify(date);
		policyOrder.setPolicyId(policyId);
		policyOrder.setMemberPhone(member.getPhone());
		policyOrder.setOrderAmount(orderAmount);
		policyOrder.setAreaCode(areaCode);
		policyOrder.setAreaName(areaName);
		policyOrder.setIdNo(idNo);
		policyOrder.setConfirmTime(StringUtil.isEmpty(confirmTime)?date:DateUtil.fomatDate(confirmTime,DateUtil.sdfTime));
		policyOrder.setPolicyStatus(policyStatus);
		result = ysPolicyOrderMapper.insert(policyOrder);
		//
		int activateCount = ysObdMapper.selectMemberIdActivateCount(member.getId());
		if(activateCount == 0) {
			throw new ApplicationException("会员(memberId:" + thirdUserId + ")尚未激活OBD!");
		}
		if(member.getFromType() == null){
			throw new ApplicationException("会员(memberId:" + thirdUserId + ")没有发展来源类型!");
		}
        if(member.getFromType() == BizEnum.MemberDevelopeFrom.AgentDevelope.getType()){
			agent = agentMapper.selectByPrimaryKey(member.getFromId());
			if(agent.getAgentLevel()==1){
				firstAgent = agent;
			}else if(agent.getAgentLevel()==2){
				secondAgent = agent;
				firstAgent = agentMapper.selectParentAgentProfitInfoById(agent.getId());
			}else if(agent.getAgentLevel()==3){
				thirdAgent = agent;
				secondAgent = agentMapper.selectParentAgentProfitInfoById(agent.getId());
				firstAgent = agentMapper.selectParentAgentProfitInfoById(secondAgent.getId());
			}else if(agent.getAgentLevel()>3){
				throw new ApplicationException("会员(memberId:" + thirdUserId + ")代理商等级超过3级!");
			}
		}else if(member.getFromType() == BizEnum.MemberDevelopeFrom.ShopDevelope.getType()){
			shop = shopMapper.selectByPrimaryKey(member.getFromId());
			parentAgent = agentMapper.selectAgentProfitInfoByShopId(shop.getId(),member.getGroupId());
			if(parentAgent.getAgentLevel() ==1){
				firstAgent = parentAgent;
			}else if(parentAgent.getAgentLevel() == 2){
				secondAgent = parentAgent;
				firstAgent = agentMapper.selectParentAgentProfitInfoById(parentAgent.getId());
			}
		}

		city = policyProfitCityMapper.selectValidRule(member.getGroupId(),areaCode);
		if(!"0000".equals(areaCode) && city == null){
			city = policyProfitCityMapper.selectValidRule(member.getGroupId(),"0000");
		}
		if(city == null){
			throw new ApplicationException("地区(city:" + areaCode + ")分润比率未设置!");
		}
        //取得分润总额
		Long totalProfit = 0L;
        Long tmpProfit = 0L;//临时变量

		String tradeMonth = DateUtil.fomatDate(date, DateUtil.sdfDayss);
		//如果有效期时间大于修改时间且交易月分
		if(city.getValidTime() != null && city.getValidTime().compareTo(city.getGmtModify()) > 0
				&& tradeMonth.equals(DateUtil.fomatDate(city.getGmtModify(), DateUtil.sdfDayss))){
			//取老值
			city.setOldProfit(city.getOldProfit()==null?0:city.getOldProfit());
			totalProfit = (Long.parseLong(city.getOldProfit().toString()) * Long.parseLong(orderAmount.toString()))/10000;
		}else{
			//取新值
			city.setProfit(city.getProfit()==null?0:city.getProfit());
			totalProfit = (Long.parseLong(city.getProfit().toString()) * Long.parseLong(orderAmount.toString()))/10000;
		}
		if(totalProfit == null || totalProfit <= 0){
			throw new ApplicationException("分润总额不能小于0!");
		}

		//先查一级代理商
		rule = policyProfitRuleMapper.selectAgentValidRule(member.getGroupId(),firstAgent.getId());
		if(rule == null){
			rule = policyProfitRuleMapper.selectGroupValidRule(member.getGroupId());
		}

		if(rule==null)
			throw new ApplicationException("保单分润规则未设置!");

		Integer platformProfit = 0;
		Integer userProfit = 0;
		Integer profit1 = 0;
		Integer profit2 = 0;
		Integer profit3 = 0;


		//如果有效期时间大于修改时间且交易月分
		if(rule.getValidTime() != null && rule.getValidTime().compareTo(rule.getGmtModify()) > 0
				&& tradeMonth.equals(DateUtil.fomatDate(rule.getGmtModify(), DateUtil.sdfDayss))){
			//取老值
			platformProfit = rule.getOldPlatformProfit()==null?0:rule.getOldPlatformProfit();
			userProfit = rule.getOldUserProfit()==null?0:rule.getOldUserProfit();
			profit1 = rule.getOldProfit1()==null?0:rule.getOldProfit1();
			profit2 = rule.getOldProfit2()==null?0:rule.getOldProfit2();
			profit3 = rule.getOldProfit2()==null?0:rule.getOldProfit3();
		}else{
			//			1代表立即生效
			if (Tools.isEmpty(rule.getReverseField2()+"")){
				//取新值
				platformProfit = rule.getPlatformProfit()==null?0:rule.getPlatformProfit();
				userProfit = rule.getUserProfit()==null?0:rule.getUserProfit();
				profit1 = rule.getProfit1()==null?0:rule.getProfit1();
				profit2 = rule.getProfit2()==null?0:rule.getProfit2();
				profit3 = rule.getProfit3()==null?0:rule.getProfit3();
			}else{
				if (rule.getReverseField2()==1){
					//取新值
					platformProfit = rule.getNewPlatformProfit()==null?0:rule.getNewPlatformProfit();
					userProfit = rule.getNewUserProfit()==null?0:rule.getNewUserProfit();
					profit1 = rule.getNewProfit1()==null?0:rule.getNewProfit1();
					profit2 = rule.getNewProfit2()==null?0:rule.getNewProfit2();
					profit3 = rule.getNewProfit3()==null?0:rule.getNewProfit3();
				}else{
					//取新值
					platformProfit = rule.getPlatformProfit()==null?0:rule.getPlatformProfit();
					userProfit = rule.getUserProfit()==null?0:rule.getUserProfit();
					profit1 = rule.getProfit1()==null?0:rule.getProfit1();
					profit2 = rule.getProfit2()==null?0:rule.getProfit2();
					profit3 = rule.getProfit3()==null?0:rule.getProfit3();
				}

			}

		}

		profit.setGmtCreate(date);
		profit.setGmtModified(date);
		profit.setGroupId(member.getGroupId());
		profit.setProfitType(ProfitEnum.ProfitType.Policy.getType());
		profit.setProfit(totalProfit.intValue());
		tmpProfit = (totalProfit*Long.parseLong(platformProfit.toString()))/10000;
		profit.setGroupProfit(tmpProfit.intValue());
		profit.setMemberId(member.getId());
		tmpProfit = (totalProfit*Long.parseLong(userProfit.toString()))/10000;
		profit.setDevelopeProfit(tmpProfit.intValue());
		profit.setProduceMemberid(member.getId());

		if(agent != null){
			if(agent.getAgentLevel()==1){
				profit.setFirstAgentId(agent.getId());
				tmpProfit = (totalProfit*(profit1+profit2+profit3))/10000;
				profit.setFirstAgentProfit(tmpProfit.intValue());
			}else if(agent.getAgentLevel()==2){
				profit.setSecondAgentId(agent.getId());
				tmpProfit = (totalProfit*(profit2+profit3))/10000;
				profit.setSecondAgentProfit(tmpProfit.intValue());
				profit.setFirstAgentId(firstAgent.getId());
				tmpProfit = (totalProfit*profit1)/10000;
				profit.setFirstAgentProfit(tmpProfit.intValue());
			}else if(agent.getAgentLevel()==3){
				profit.setThirdAgentId(agent.getId());
				tmpProfit = (totalProfit*profit3)/10000;
				profit.setThirdAgentProfit(tmpProfit.intValue());
				profit.setSecondAgentId(secondAgent.getId());
				tmpProfit = (totalProfit*profit2)/10000;
				profit.setSecondAgentProfit(tmpProfit.intValue());
				profit.setFirstAgentId(firstAgent.getId());
				tmpProfit = (totalProfit*profit1)/10000;
				profit.setFirstAgentProfit(tmpProfit.intValue());
			}
			profit.setProduceAgentid(agent.getId());
		}else if(shop != null){
			profit.setShopId(shop.getId());
			tmpProfit = (totalProfit*profit3)/10000;
			profit.setShopProfit(tmpProfit.intValue());
			profit.setProduceShopid(shop.getId());

			if(parentAgent.getAgentLevel() ==1){
				profit.setFirstAgentId(parentAgent.getId());
				tmpProfit = (totalProfit*(profit1+profit2))/10000;
				profit.setFirstAgentProfit(tmpProfit.intValue());
				profit.setProduceAgentid(parentAgent.getId());
			}else if(parentAgent.getAgentLevel() == 2){
				profit.setSecondAgentId(parentAgent.getId());
				tmpProfit = (totalProfit*profit2)/10000;
				profit.setSecondAgentProfit(tmpProfit.intValue());
				profit.setFirstAgentId(firstAgent.getId());
				tmpProfit = (totalProfit*profit1)/10000;
				profit.setFirstAgentProfit(tmpProfit.intValue());
			}
		}
		profit.setProfitStatus(ProfitEnum.ProfitStatus.Profited.getType());
		profit.setOrderId((long)policyOrder.getId());
		profit.setOrderNo(policyId);
		//profit.setMemo(creditCardNo);
		//profit.setMemberId(memberId);

		result = profitMapper.insert(profit);

		return result;
	}



	@Override
	public YsCityListOutDTO queryYsCityList(YsCity ysCity) throws ApplicationException {
		YsCityListOutDTO ysCityListOutDTO=new YsCityListOutDTO();
    	List<String> cityList=ysCityMapper.queryYsCityList();
		List<YsPolicyProfitCity> selectCityList=policyProfitCityMapper.queryYsPolicyProfitCityList(ysCity.getGroupId());
		ArrayList<String> tempList= new ArrayList<String>();
		for (String city: cityList) {
			boolean flag=true;
			for (YsPolicyProfitCity tempAgent: selectCityList) {
				if (city.equals(tempAgent.getCityName())){
					flag=false;

				}

			}
			if (flag){
				tempList.add(city);
			}

		}

		ysCityListOutDTO.setYsCityList(tempList);
		return ysCityListOutDTO;
	}

	@Override
	public int addCityToPolicyList(YsCity ysCity) throws ApplicationException {

		for (String tempCity:
		ysCity.getCityList() ) {
			YsPolicyProfitCity ysPolicyProfitCity=new YsPolicyProfitCity();

			if (!Tools.isEmpty(tempCity)){
				YsCity ysCity2=ysCityMapper.queryCityCode(tempCity);
				ysPolicyProfitCity.setCityCode(ysCity2.getCityCode());
				ysPolicyProfitCity.setGmtCreate(new Date());
				ysPolicyProfitCity.setGmtModify(new Date());
				ysPolicyProfitCity.setProfit(ysCity.getCityProfit());
				ysPolicyProfitCity.setNewProfit(ysCity.getNewCityProfit());
				ysPolicyProfitCity.setGroupId(ysCity.getGroupId());
				ysPolicyProfitCity.setCityName(tempCity);
				int status=policyProfitCityMapper.insert(ysPolicyProfitCity);
				if (status<=0){
					return status;
				}
			}

		}
		return 1;
			





			

	}
}
